package com.java.business.system.database.service;

import java.util.List;

import javax.management.RuntimeErrorException;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.java.business.system.database.bean.SyncBase;
import com.java.business.system.database.dao.SyncBaseMapper;
import com.java.core.utils.IdUtils;

@Transactional
@Service
public class SyncBaseService {

	@Autowired
	private SyncBaseMapper mapper;

	public void add(SyncBase base) throws RuntimeException {
		base.setId(IdUtils.uuid());
		mapper.add(base);
	}

	public void update(SyncBase base) throws RuntimeException {
		mapper.update(base);
	}

	public void updateTotal() throws RuntimeException {
		List<SyncBase> list = getList(new SyncBase());
		for (SyncBase base : list) {
			mapper.updateTotal(base);
		}
	}

	public void delete(SyncBase base) throws RuntimeException {
		mapper.delete(base.getId());
	}

	public List<SyncBase> getList(SyncBase base) {
		return mapper.getList(base);
	}

	public void sync(String[] tables, String[] dblinks) throws RuntimeException {
		for (int i = 0; i < tables.length; i++) {
			String tablename = tables[i];
			String dblink = dblinks[i];
			List<String> keys = mapper.getKey(tablename);
			if (keys == null || keys.size() == 0) {
				throw new RuntimeErrorException(null, "表【" + tablename
						+ "】不存在或者没有设置主键！");
			}
			String tempKey = "";
			for (String key : keys) {
				if (tempKey.length() > 0) {
					tempKey += "||";
				}
				tempKey += key;
			}
			mapper.sync(tablename, tempKey, dblink);
		}
		// 同步后更新数据量
		updateTotal();
	}
}
